import React, { useState, useEffect } from "react";
import { Card, Tabs, Button, Table, Input, Select, Row, Col, Form, Modal, Tag, Cascader, message } from 'antd';
import { PageHeaderWrapper } from "@ant-design/pro-layout";
import styles from './index.less'
import { DownOutlined, UpOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { Loading, connect } from 'umi';

import OperaPrompt from '../../../components/OperaPrompt'
import GoodsType from './goods_type'
import OffShelf from './off_shelf'
import request from '@/utils/request'

const { confirm } = Modal
const { TabPane } = Tabs;
const { Option } = Select;
const { TextArea } = Input;

const statusList = [
  {
    title: "出售中",
    key: "1"
  },
  {
    title: "已下架",
    key: "2"
  },
  {
    title: "库存预警",
    key: "3"
  },
];

export default connect(({ goods, loading }: { goods: any, loading: Loading }) =>
  ({ tableData: goods.tableData, searchParams: goods.searchParams, tableLoading: loading.effects['goods/fetchList'] }))
  ((props: any) => {

    const { tableData, dispatch, page, tableLoading, searchParams } = props

    const [statusKey, setStatusKey] = useState("1");
    const [selectedKeys, setSelectedKeys] = useState([]);
    const [multSearch, setMultSearch] = useState(false);
    const [visable, setViable] = useState(false)
    const [offShelfVisable, setOffShelfVisable] = useState(false)
    const [form] = Form.useForm()
    const [searchForm] = Form.useForm()

    const columns: any = [
      {
        title: '商品名称',
        dataIndex: 'name',
        width: "360px",
        render: (text: any, record: any) => <div style={{ display: "flex", alignItems: "center" }}>
          <img src={record.logo} style={{ width: "74px", display: "block" }} />
          <div style={{ display: "flex", flexDirection: "column", marginLeft: "4px" }}>
            <span style={{ fontSize: "12px", color: "#999" }}>创建时间：{record.created_at}</span>
            <span style={{ fontWeight: 600 }}>{text}</span>
            <span style={{ fontSize: "12px", color: "#999" }}>{record.sell_point}</span>
          </div>
        </div>,
      },
      {
        title: '店铺名称',
        dataIndex: 'store_name',
        render: (text: any) => <a>{text}</a>,
      },
      {
        title: '价格（元）',
        dataIndex: 'price',
        align: "center",
      },
      {
        title: '库存',
        dataIndex: 'total_stock',
        align: "center",
      },
      {
        title: '销量',
        dataIndex: 'sales',
        align: "center",
      },
      {
        title: '商品状态',
        dataIndex: 'status_title',
        align: "center",
        render: (text: any) => <Tag color="blue">{text}</Tag>,
      },
      {
        title: '审核状态',
        dataIndex: 'audit_status_title',
        align: "center",
        render: (text: any) => <Tag color="green">{text}</Tag>,
      },
      {
        title: '商品类型',
        dataIndex: 'type_title',
        render: (text: any) => <Tag color="cyan">{text}</Tag>
      },
      {
        title: '操作',
        width: "220px",
        align: "center",
        render: (text: any, record: any) => (
          <>
            <Button size="small" type="primary" ghost style={{ margin: "0 5px" }}>修改</Button>
            <Button size="small" onClick={() => {
              form.setFieldsValue({ goods_id: record.id })
              setOffShelfVisable(true)
            }}>违规下架</Button>
          </>
        ),
      },
    ];


    const searchFinish = (values: any) => {
      setSelectedKeys([])
      dispatch({
        type: "goods/fetchList",
        payload: {
          current: page,
          ...values,
          status: statusKey
        }
      })
    }
    const SearchForm = () => {
      return (
        <div style={{ float: "right" }}>
          <Form layout="inline" form={searchForm} onFinish={searchFinish}>
            <Form.Item label="商品名称：" name="goods_name">
              <Input placeholder="请输入商品名称" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" style={{ marginRight: "8px" }} htmlType="submit">搜索</Button>
              <a onClick={() => {
                setMultSearch(true)
              }}>展开<DownOutlined /></a>
            </Form.Item>
          </Form>
        </div>
      );
    }
    const MultSearch = () => {
      return (
        <Form form={searchForm}
          onFinish={searchFinish}
        >
          <Row gutter={16}>
            <Col span={4}>
              <Form.Item label="商品名称：" name="goods_name" style={{ marginBottom: "10px" }}>
                <Input placeholder="请输入商品名称" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item label="店铺名称：" name="store_name" style={{ marginBottom: "10px" }}>
                <Input placeholder="请输入店铺名称" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item label="商品编码：" name="goods_identify" style={{ marginBottom: "10px" }}>
                <Input placeholder="请输入商品编码" />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item label="商品标签：" name="tag_id" style={{ marginBottom: "10px" }}>
                <Select placeholder="请选择商品标签">
                  {/* <Option value={0} key={-1}>请选择</Option> */}
                  {
                    searchParams.tagList.map((item: any, inx: number) => {
                      return <Option value={item.id} key={inx}>
                        {item.title}</Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item label="商品分类：" name="category_id" style={{ marginBottom: "10px" }}>
                <Cascader
                  options={searchParams.categoryTrees}
                />
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item label="商品品牌：" name="brand_id" style={{ marginBottom: "10px" }}>
                <Select placeholder="请选择商品分类">
                  {/* <Option value={0} key={-1}>请选择</Option> */}
                  {
                    searchParams.brandList.map((item: any, inx: number) => {
                      return <Option value={item.id} key={inx}>
                        {item.title}</Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col span={8}>
              <Button type="primary" style={{ marginRight: "8px" }} htmlType="submit">搜索</Button>
              <Button style={{ marginRight: "8px" }} htmlType="reset" onClick={() => {
                searchForm.resetFields()
                searchForm.submit()
              }}>重置</Button>
              <a onClick={() => {
                setMultSearch(false)
              }}>收起<UpOutlined /></a>
            </Col>
          </Row>
        </Form>
      );
    }
    const ToolBtn = () => {
      return (
        <div style={{ paddingTop: "10px" }}>
          <div>
            <div className={styles.toolBtn} style={{ float: "left" }}>
              <Button type="primary" onClick={() => {
                setViable(true)
              }}>发布商品</Button>
              <Button danger onClick={() => {
                confirm({
                  title: '是否下架这些选中的商品？',
                  icon: <ExclamationCircleOutlined />,
                  onOk() {
                    if (selectedKeys.length < 1) {
                      message.warn("请选择你要操作的选项")
                      return
                    }
                    request('/goods/destroy', {
                      method: "delete",
                      params: { ids: selectedKeys }
                    }).then((result: any) => {
                      if (result.code === 200) {
                        message.success(result.message)
                        searchForm.submit()
                      }
                    })
                  }
                })
              }}>批量删除</Button>
              {statusKey === "2" && <Button onClick={() => {
                if (selectedKeys.length < 1) {
                  message.warn("请选择你要操作的选项")
                  return
                }
                confirm({
                  title: '是否下架这些选中的商品？',
                  icon: <ExclamationCircleOutlined />,
                  onOk() {
                    console.log(selectedKeys)
                    request('/goods/on-shelf', {
                      method: "put",
                      params: { ids: selectedKeys }
                    }).then((result: any) => {
                      if (result.code === 200) {
                        message.success(result.message)
                        searchForm.submit()
                      }
                    })
                  }
                })
              }}>上架</Button>}
              {
                statusKey === "1" && <Button onClick={() => {
                  if (selectedKeys.length < 1) {
                    message.warn("请选择你要操作的选项")
                    return
                  }
                  confirm({
                    title: '是否下架这些选中的商品？',
                    icon: <ExclamationCircleOutlined />,
                    onOk() {
                      request('/goods/off-shelf', {
                        method: "put",
                        params: { ids: selectedKeys }
                      }).then((result: any) => {
                        if (result.code === 200) {
                          message.success(result.message)
                          searchForm.submit()
                        }
                      })
                    }
                  })
                }}>下架</Button>
              }
            </div>
            {!multSearch && <SearchForm />}
            <div style={{ clear: "both" }} />
          </div>
          {multSearch && <MultSearch />}
        </div >
      );
    };

    const rowSelection = {
      selectedRowKeys: selectedKeys,
      onChange: (selectedRowKeys: any) => {
        setSelectedKeys(selectedRowKeys)
      },
    };

    useEffect(() => {
      dispatch({
        type: "goods/fetchList",
        payload: {
          current: page
        }
      })
    }, [])
    useEffect(() => {
      dispatch({
        type: "goods/getSearchParams"
      })
    }, [])

    return (
      <PageHeaderWrapper title={false}>
        <Card bordered={false}>
          <OperaPrompt dataList={[
            "当前显示的是商家发布过的所有商品，当商品处于上架状态时前台显示",
            "虚拟商品用户购买之后可以通过订单核销进行商品核销处理。",
            "如果商家的商品操作违规，平台可以操作违规下架，违规下架的商品需要商家编辑审核之后才能重新上架"
          ]} />
          <ToolBtn />
          <Tabs defaultActiveKey="1" onChange={(activeKey) => {
            setStatusKey(activeKey)
            searchForm.submit()
          }}>
            {
              statusList.map((item) =>
                <TabPane key={item.key} tab={item.title} style={{ outline: "none" }}>
                  {item.key === statusKey &&
                    <Table rowKey="id"
                      columns={columns}
                      dataSource={tableData.list}
                      rowSelection={rowSelection}
                      pagination={{ ...tableData.pagination }}
                      loading={tableLoading}
                      onChange={(pagination: any, filters: any, sorter: any, extra: any) => {
                        dispatch({
                          type: "goods/fetchList",
                          payload: {
                            current: pagination.current
                          }
                        })
                      }}
                    />
                  }
                </TabPane>
              )
            }
          </Tabs>
          <Modal
            visible={visable}
            footer={null}
            onCancel={() => setViable(false)}
            width="40%"
          >
            <GoodsType />
          </Modal>
          <Modal
            title="违规下架原因"
            visible={offShelfVisable}
            onCancel={() => setOffShelfVisable(false)}
            getContainer={false}
            onOk={() => form.submit()}
          >
            <Form
              onFinish={(values: any) => {
                console.log(values);
                request('/goods/invalid-shelf', {
                  method: "put",
                  params: { ids: [values.goods_id] },
                  data: { reason: values.reason }
                }).then((result: any) => {
                  if (result.code === 200) {
                    setOffShelfVisable(false)
                    message.success(result.message)
                    searchForm.submit()
                  }
                })
              }}
              form={form}
            >
              <Form.Item name="reason" required rules={[{ required: true, message: '请输入违规下架原因' }]}>
                <TextArea placeholder="请输入违规下架原因" rows={3} />
              </Form.Item>
              <Form.Item name="goods_id" noStyle>
                <Input type="hidden" />
              </Form.Item>
            </Form>
          </Modal>
        </Card>
      </PageHeaderWrapper>
    )
  })
